<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抖音数据统计分析系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            color: white;
            text-align: center;
            padding: 30px;
            position: relative;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="2" fill="rgba(255,255,255,0.1)"/><circle cx="80" cy="80" r="3" fill="rgba(255,255,255,0.1)"/><circle cx="40" cy="70" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="30" r="2" fill="rgba(255,255,255,0.1)"/></svg>');
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }
        
        .nav-tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        .nav-tab {
            flex: 1;
            padding: 15px 20px;
            text-align: center;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            font-weight: 500;
            color: #495057;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .nav-tab:hover {
            background: #e9ecef;
            color: #007bff;
        }
        
        .nav-tab.active {
            background: white;
            color: #007bff;
            border-bottom: 3px solid #007bff;
        }
        
        .tab-content {
            padding: 30px;
        }
        
        .tab-pane {
            display: none;
        }
        
        .tab-pane.active {
            display: block;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #333;
            font-size: 14px;
        }
        
        .form-group input, .form-group select, .form-group textarea {
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }
        
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }
        
        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px 5px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,123,255,0.3);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(40,167,69,0.3);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s ease;
            border-left: 5px solid;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-card.plays { border-left-color: #ff6b6b; }
        .stat-card.likes { border-left-color: #4ecdc4; }
        .stat-card.comments { border-left-color: #45b7d1; }
        .stat-card.shares { border-left-color: #96ceb4; }
        .stat-card.followers { border-left-color: #ffeaa7; }
        .stat-card.conversion { border-left-color: #dda0dd; }
        
        .stat-value {
            font-size: 2.5em;
            font-weight: 700;
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        .stat-label {
            font-size: 1em;
            color: #7f8c8d;
            margin-bottom: 10px;
        }
        
        .stat-change {
            font-size: 0.9em;
            font-weight: 600;
            padding: 5px 10px;
            border-radius: 20px;
        }
        
        .stat-change.positive {
            background: #d4edda;
            color: #155724;
        }
        
        .stat-change.negative {
            background: #f8d7da;
            color: #721c24;
        }
        
        .chart-container {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin: 20px 0;
        }
        
        .chart-title {
            font-size: 1.5em;
            font-weight: 600;
            margin-bottom: 20px;
            color: #2c3e50;
            text-align: center;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .data-table th {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
        }
        
        .data-table td {
            padding: 15px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .data-table tr:hover {
            background: #f8f9fa;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin: 20px 0;
            font-weight: 500;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }
        
        .progress-bar {
            width: 100%;
            height: 10px;
            background: #e9ecef;
            border-radius: 5px;
            overflow: hidden;
            margin: 10px 0;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4ecdc4, #45b7d1);
            transition: width 0.3s ease;
        }
        
        .section-title {
            font-size: 1.8em;
            font-weight: 600;
            margin: 30px 0 20px 0;
            color: #2c3e50;
            border-bottom: 3px solid #007bff;
            padding-bottom: 10px;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .nav-tabs {
                flex-direction: column;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .container {
                margin: 10px;
                border-radius: 10px;
            }
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎵 抖音数据统计分析系统</h1>
            <p>让数据驱动内容创作，精准把握用户需求</p>
        </div>
        
        <div class="nav-tabs">
            <button class="nav-tab active" onclick="switchTab('daily')">📝 每日记录</button>
            <button class="nav-tab" onclick="switchTab('weekly')">📊 周度分析</button>
            <button class="nav-tab" onclick="switchTab('monthly')">📈 月度分析</button>
            <button class="nav-tab" onclick="switchTab('dashboard')">🎯 数据仪表板</button>
        </div>
        
        <!-- 每日记录表单 -->
        <div id="daily" class="tab-pane active">
            <div class="tab-content">
                <h2 class="section-title">📝 每日数据记录</h2>
                
                <div class="alert alert-info">
                    <strong>💡 使用提示：</strong> 请每日及时记录数据，系统将自动生成周报和月报分析。建议在晚上21:00左右记录当日最终数据。
                </div>
                
                <form id="dailyForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="date">📅 记录日期</label>
                            <input type="date" id="date" name="date" required>
                        </div>
                        <div class="form-group">
                            <label for="recorder">👤 记录人</label>
                            <input type="text" id="recorder" name="recorder" placeholder="输入记录人姓名">
                        </div>
                        <div class="form-group">
                            <label for="videoCount">🎬 发布视频数量</label>
                            <input type="number" id="videoCount" name="videoCount" min="0" placeholder="今日发布视频数">
                        </div>
                    </div>
                    
                    <h3 class="section-title">📊 播放数据</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="totalPlays">▶️ 总播放量</label>
                            <input type="number" id="totalPlays" name="totalPlays" min="0" placeholder="今日总播放量">
                        </div>
                        <div class="form-group">
                            <label for="avgPlayTime">⏱️ 平均播放时长(秒)</label>
                            <input type="number" id="avgPlayTime" name="avgPlayTime" min="0" step="0.1" placeholder="平均播放时长">
                        </div>
                        <div class="form-group">
                            <label for="completionRate">✅ 完播率(%)</label>
                            <input type="number" id="completionRate" name="completionRate" min="0" max="100" step="0.1" placeholder="完播率">
                        </div>
                    </div>
                    
                    <h3 class="section-title">❤️ 互动数据</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="totalLikes">👍 总点赞数</label>
                            <input type="number" id="totalLikes" name="totalLikes" min="0" placeholder="今日总点赞数">
                        </div>
                        <div class="form-group">
                            <label for="totalComments">💬 总评论数</label>
                            <input type="number" id="totalComments" name="totalComments" min="0" placeholder="今日总评论数">
                        </div>
                        <div class="form-group">
                            <label for="totalShares">🔄 总分享数</label>
                            <input type="number" id="totalShares" name="totalShares" min="0" placeholder="今日总分享数">
                        </div>
                        <div class="form-group">
                            <label for="totalCollects">⭐ 总收藏数</label>
                            <input type="number" id="totalCollects" name="totalCollects" min="0" placeholder="今日总收藏数">
                        </div>
                    </div>
                    
                    <h3 class="section-title">👥 用户增长</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="newFollowers">➕ 新增粉丝</label>
                            <input type="number" id="newFollowers" name="newFollowers" placeholder="今日新增粉丝数">
                        </div>
                        <div class="form-group">
                            <label for="unfollowers">➖ 取关人数</label>
                            <input type="number" id="unfollowers" name="unfollowers" min="0" placeholder="今日取关人数">
                        </div>
                        <div class="form-group">
                            <label for="totalFollowers">👥 总粉丝数</label>
                            <input type="number" id="totalFollowers" name="totalFollowers" min="0" placeholder="截止今日总粉丝数">
                        </div>
                    </div>
                    
                    <h3 class="section-title">💰 转化数据</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="privateMessages">📧 私信咨询数</label>
                            <input type="number" id="privateMessages" name="privateMessages" min="0" placeholder="今日私信咨询数">
                        </div>
                        <div class="form-group">
                            <label for="wechatAdds">📱 微信添加数</label>
                            <input type="number" id="wechatAdds" name="wechatAdds" min="0" placeholder="转化到微信人数">
                        </div>
                        <div class="form-group">
                            <label for="trialBookings">🎯 体验预约数</label>
                            <input type="number" id="trialBookings" name="trialBookings" min="0" placeholder="体验课预约人数">
                        </div>
                        <div class="form-group">
                            <label for="conversions">💎 直接成交数</label>
                            <input type="number" id="conversions" name="conversions" min="0" placeholder="当日直接成交人数">
                        </div>
                    </div>
                    
                    <h3 class="section-title">💵 成本数据</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="contentCost">🎬 内容制作成本</label>
                            <input type="number" id="contentCost" name="contentCost" min="0" step="0.01" placeholder="内容制作费用">
                        </div>
                        <div class="form-group">
                            <label for="adCost">📢 广告投放成本</label>
                            <input type="number" id="adCost" name="adCost" min="0" step="0.01" placeholder="广告投放费用">
                        </div>
                        <div class="form-group">
                            <label for="laborCost">👥 人力成本</label>
                            <input type="number" id="laborCost" name="laborCost" min="0" step="0.01" placeholder="人力投入成本">
                        </div>
                    </div>
                    
                    <h3 class="section-title">📝 备注信息</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="notes">📋 异常情况/备注</label>
                            <textarea id="notes" name="notes" rows="3" placeholder="记录今日特殊情况、异常数据或其他需要说明的内容..."></textarea>
                        </div>
                    </div>
                    
                    <div style="text-align: center; margin-top: 30px;">
                        <button type="submit" class="btn btn-primary">💾 保存今日数据</button>
                        <button type="button" class="btn btn-success" onclick="exportData()">📊 导出数据</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 周度分析 -->
        <div id="weekly" class="tab-pane">
            <div class="tab-content">
                <h2 class="section-title">📊 周度数据分析</h2>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="weekSelect">📅 选择周次</label>
                        <select id="weekSelect" onchange="updateWeeklyData()">
                            <option value="">选择要分析的周次</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="generateWeeklyReport()">📈 生成周报</button>
                    </div>
                </div>
                
                <div id="weeklyStats" class="stats-grid">
                    <div class="stat-card plays">
                        <div class="stat-value" id="weeklyPlays">0</div>
                        <div class="stat-label">周播放量</div>
                        <div class="stat-change positive" id="weeklyPlaysChange">+0%</div>
                    </div>
                    <div class="stat-card likes">
                        <div class="stat-value" id="weeklyLikes">0</div>
                        <div class="stat-label">周点赞数</div>
                        <div class="stat-change positive" id="weeklyLikesChange">+0%</div>
                    </div>
                    <div class="stat-card followers">
                        <div class="stat-value" id="weeklyFollowers">0</div>
                        <div class="stat-label">周增粉数</div>
                        <div class="stat-change positive" id="weeklyFollowersChange">+0%</div>
                    </div>
                    <div class="stat-card conversion">
                        <div class="stat-value" id="weeklyConversions">0</div>
                        <div class="stat-label">周转化数</div>
                        <div class="stat-change positive" id="weeklyConversionsChange">+0%</div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📈 本周趋势分析</div>
                    <canvas id="weeklyChart" width="400" height="200"></canvas>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">🎯 内容类型效果对比</div>
                    <canvas id="contentTypeChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <!-- 月度分析 -->
        <div id="monthly" class="tab-pane">
            <div class="tab-content">
                <h2 class="section-title">📈 月度数据分析</h2>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="monthSelect">📅 选择月份</label>
                        <select id="monthSelect" onchange="updateMonthlyData()">
                            <option value="">选择要分析的月份</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="generateMonthlyReport()">📊 生成月报</button>
                    </div>
                </div>
                
                <div id="monthlyStats" class="stats-grid">
                    <div class="stat-card plays">
                        <div class="stat-value" id="monthlyPlays">0</div>
                        <div class="stat-label">月播放量</div>
                        <div class="stat-change positive" id="monthlyPlaysChange">+0%</div>
                    </div>
                    <div class="stat-card likes">
                        <div class="stat-value" id="monthlyLikes">0</div>
                        <div class="stat-label">月点赞数</div>
                        <div class="stat-change positive" id="monthlyLikesChange">+0%</div>
                    </div>
                    <div class="stat-card followers">
                        <div class="stat-value" id="monthlyFollowers">0</div>
                        <div class="stat-label">月增粉数</div>
                        <div class="stat-change positive" id="monthlyFollowersChange">+0%</div>
                    </div>
                    <div class="stat-card conversion">
                        <div class="stat-value" id="monthlyConversions">0</div>
                        <div class="stat-label">月转化数</div>
                        <div class="stat-change positive" id="monthlyConversionsChange">+0%</div>
                    </div>
                    <div class="stat-card shares">
                        <div class="stat-value" id="monthlyROI">0</div>
                        <div class="stat-label">投资回报率</div>
                        <div class="stat-change positive" id="monthlyROIChange">+0%</div>
                    </div>
                    <div class="stat-card comments">
                        <div class="stat-value" id="monthlyEngagement">0%</div>
                        <div class="stat-label">平均互动率</div>
                        <div class="stat-change positive" id="monthlyEngagementChange">+0%</div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📊 月度综合分析</div>
                    <canvas id="monthlyChart" width="400" height="200"></canvas>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">💰 转化漏斗分析</div>
                    <canvas id="funnelChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <!-- 数据仪表板 -->
        <div id="dashboard" class="tab-pane">
            <div class="tab-content">
                <h2 class="section-title">🎯 数据仪表板</h2>
                
                <div class="alert alert-info">
                    <strong>📊 实时概览：</strong> 展示最新数据趋势和关键指标，帮助您快速了解账号整体表现。
                </div>
                
                <div class="stats-grid">
                    <div class="stat-card plays">
                        <div class="stat-value" id="dashboardTotalPlays">0</div>
                        <div class="stat-label">累计播放量</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: 75%"></div>
                        </div>
                    </div>
                    <div class="stat-card followers">
                        <div class="stat-value" id="dashboardTotalFollowers">0</div>
                        <div class="stat-label">总粉丝数</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: 60%"></div>
                        </div>
                    </div>
                    <div class="stat-card conversion">
                        <div class="stat-value" id="dashboardTotalConversions">0</div>
                        <div class="stat-label">累计转化数</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: 45%"></div>
                        </div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📈 近30天趋势分析</div>
                    <canvas id="dashboardTrendChart" width="400" height="200"></canvas>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">🎯 关键指标对比</div>
                    <canvas id="kpiCompareChart" width="400" height="200"></canvas>
                </div>
                
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>📅 日期</th>
                            <th>🎬 视频数</th>
                            <th>▶️ 播放量</th>
                            <th>👍 点赞数</th>
                            <th>👥 新增粉丝</th>
                            <th>💎 转化数</th>
                            <th>📊 互动率</th>
                        </tr>
                    </thead>
                    <tbody id="recentDataTable">
                        <!-- 最近数据将在这里显示 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 密码验证
        function checkPassword() {
            const savedPassword = localStorage.getItem('systemPassword');
            if (!savedPassword) {
                const newPassword = prompt('首次使用，请设置访问密码（6位数字）：');
                if (newPassword && newPassword.length === 6 && /^\d+$/.test(newPassword)) {
                    localStorage.setItem('systemPassword', newPassword);
                    alert('✅ 密码设置成功！请分享给团队成员。');
                } else {
                    alert('❌ 密码格式错误，请设置6位数字密码');
                    window.location.href = 'about:blank';
                    return false;
                }
            } else {
                const inputPassword = prompt('请输入6位数字访问密码：');
                if (inputPassword !== savedPassword) {
                    alert('❌ 密码错误！');
                    window.location.href = 'about:blank';
                    return false;
                }
            }
            return true;
        }
        
        // 检查密码后再初始化
        if (!checkPassword()) return;
        
        // 数据存储
        let dailyData = JSON.parse(localStorage.getItem('douyinDailyData') || '[]');
        
        // 标签页切换
        function switchTab(tabName) {
            // 隐藏所有标签页
            document.querySelectorAll('.tab-pane').forEach(pane => {
                pane.classList.remove('active');
            });
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
            
            // 根据标签页更新数据
            if (tabName === 'weekly') {
                updateWeekSelect();
                updateWeeklyData();
            } else if (tabName === 'monthly') {
                updateMonthSelect();
                updateMonthlyData();
            } else if (tabName === 'dashboard') {
                updateDashboard();
            }
        }
        
        // 初始化日期
        document.getElementById('date').value = new Date().toISOString().split('T')[0];
        
        // 表单提交
        document.getElementById('dailyForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = {};
            
            // 获取表单数据
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            // 计算衍生指标
            data.likeRate = data.totalPlays > 0 ? ((data.totalLikes / data.totalPlays) * 100).toFixed(2) : 0;
            data.commentRate = data.totalPlays > 0 ? ((data.totalComments / data.totalPlays) * 100).toFixed(2) : 0;
            data.shareRate = data.totalPlays > 0 ? ((data.totalShares / data.totalPlays) * 100).toFixed(2) : 0;
            data.engagementRate = data.totalPlays > 0 ? (((parseInt(data.totalLikes) + parseInt(data.totalComments) + parseInt(data.totalShares)) / data.totalPlays) * 100).toFixed(2) : 0;
            data.netFollowers = parseInt(data.newFollowers) - parseInt(data.unfollowers || 0);
            data.totalCost = parseFloat(data.contentCost || 0) + parseFloat(data.adCost || 0) + parseFloat(data.laborCost || 0);
            data.acquisitionCost = data.conversions > 0 ? (data.totalCost / data.conversions).toFixed(2) : 0;
            
            // 检查是否已存在该日期的数据
            const existingIndex = dailyData.findIndex(item => item.date === data.date);
            if (existingIndex !== -1) {
                // 更新现有数据
                dailyData[existingIndex] = data;
                alert('✅ 数据更新成功！');
            } else {
                // 添加新数据
                dailyData.push(data);
                alert('✅ 数据保存成功！');
            }
            
            // 保存到本地存储
            localStorage.setItem('douyinDailyData', JSON.stringify(dailyData));
            
            // 重置表单
            this.reset();
            document.getElementById('date').value = new Date().toISOString().split('T')[0];
        });
        
        // 更新周选择器
        function updateWeekSelect() {
            const select = document.getElementById('weekSelect');
            select.innerHTML = '<option value="">选择要分析的周次</option>';
            
            if (dailyData.length === 0) return;
            
            // 按日期排序
            const sortedData = [...dailyData].sort((a, b) => new Date(a.date) - new Date(b.date));
            const startDate = new Date(sortedData[0].date);
            const endDate = new Date(sortedData[sortedData.length - 1].date);
            
            // 生成周选项
            let currentWeek = new Date(startDate);
            currentWeek.setDate(currentWeek.getDate() - currentWeek.getDay()); // 调整到周一
            
            while (currentWeek <= endDate) {
                const weekEnd = new Date(currentWeek);
                weekEnd.setDate(weekEnd.getDate() + 6);
                
                const option = document.createElement('option');
                option.value = currentWeek.toISOString().split('T')[0];
                option.textContent = `${currentWeek.toLocaleDateString()} - ${weekEnd.toLocaleDateString()}`;
                select.appendChild(option);
                
                currentWeek.setDate(currentWeek.getDate() + 7);
            }
        }
        
        // 更新月选择器
        function updateMonthSelect() {
            const select = document.getElementById('monthSelect');
            select.innerHTML = '<option value="">选择要分析的月份</option>';
            
            if (dailyData.length === 0) return;
            
            const months = new Set();
            dailyData.forEach(data => {
                const date = new Date(data.date);
                const month = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                months.add(month);
            });
            
            [...months].sort().forEach(month => {
                const option = document.createElement('option');
                option.value = month;
                option.textContent = `${month} (${new Date(month + '-01').toLocaleDateString('zh-CN', {year: 'numeric', month: 'long'})})`;
                select.appendChild(option);
            });
        }
        
        // 更新周度数据
        function updateWeeklyData() {
            const selectedWeek = document.getElementById('weekSelect').value;
            if (!selectedWeek) return;
            
            const weekStart = new Date(selectedWeek);
            const weekEnd = new Date(weekStart);
            weekEnd.setDate(weekEnd.getDate() + 6);
            
            // 筛选本周数据
            const weekData = dailyData.filter(data => {
                const date = new Date(data.date);
                return date >= weekStart && date <= weekEnd;
            });
            
            // 计算周度统计
            const stats = calculateWeeklyStats(weekData);
            
            // 更新显示
            document.getElementById('weeklyPlays').textContent = formatNumber(stats.totalPlays);
            document.getElementById('weeklyLikes').textContent = formatNumber(stats.totalLikes);
            document.getElementById('weeklyFollowers').textContent = formatNumber(stats.totalFollowers);
            document.getElementById('weeklyConversions').textContent = formatNumber(stats.totalConversions);
            
            // 绘制周度趋势图
            drawWeeklyChart(weekData);
        }
        
        // 更新月度数据
        function updateMonthlyData() {
            const selectedMonth = document.getElementById('monthSelect').value;
            if (!selectedMonth) return;
            
            // 筛选本月数据
            const monthData = dailyData.filter(data => {
                return data.date.startsWith(selectedMonth);
            });
            
            // 计算月度统计
            const stats = calculateMonthlyStats(monthData);
            
            // 更新显示
            document.getElementById('monthlyPlays').textContent = formatNumber(stats.totalPlays);
            document.getElementById('monthlyLikes').textContent = formatNumber(stats.totalLikes);
            document.getElementById('monthlyFollowers').textContent = formatNumber(stats.totalFollowers);
            document.getElementById('monthlyConversions').textContent = formatNumber(stats.totalConversions);
            document.getElementById('monthlyROI').textContent = stats.roi + ':1';
            document.getElementById('monthlyEngagement').textContent = stats.avgEngagement + '%';
            
            // 绘制月度图表
            drawMonthlyChart(monthData);
            drawFunnelChart(stats);
        }
        
        // 计算周度统计
        function calculateWeeklyStats(data) {
            return {
                totalPlays: data.reduce((sum, item) => sum + parseInt(item.totalPlays || 0), 0),
                totalLikes: data.reduce((sum, item) => sum + parseInt(item.totalLikes || 0), 0),
                totalFollowers: data.reduce((sum, item) => sum + parseInt(item.netFollowers || 0), 0),
                totalConversions: data.reduce((sum, item) => sum + parseInt(item.conversions || 0), 0)
            };
        }
        
        // 计算月度统计
        function calculateMonthlyStats(data) {
            const totalPlays = data.reduce((sum, item) => sum + parseInt(item.totalPlays || 0), 0);
            const totalLikes = data.reduce((sum, item) => sum + parseInt(item.totalLikes || 0), 0);
            const totalFollowers = data.reduce((sum, item) => sum + parseInt(item.netFollowers || 0), 0);
            const totalConversions = data.reduce((sum, item) => sum + parseInt(item.conversions || 0), 0);
            const totalCost = data.reduce((sum, item) => sum + parseFloat(item.totalCost || 0), 0);
            const totalRevenue = totalConversions * 3000; // 假设平均客单价3000元
            
            return {
                totalPlays,
                totalLikes,
                totalFollowers,
                totalConversions,
                roi: totalCost > 0 ? (totalRevenue / totalCost).toFixed(1) : 0,
                avgEngagement: data.length > 0 ? (data.reduce((sum, item) => sum + parseFloat(item.engagementRate || 0), 0) / data.length).toFixed(2) : 0
            };
        }
        
        // 格式化数字
        function formatNumber(num) {
            if (num >= 10000) {
                return (num / 10000).toFixed(1) + '万';
            }
            return num.toString();
        }
        
        // 绘制周度趋势图
        function drawWeeklyChart(data) {
            const ctx = document.getElementById('weeklyChart').getContext('2d');
            
            // 销毁现有图表
            if (window.weeklyChart) {
                window.weeklyChart.destroy();
            }
            
            const labels = data.map(item => new Date(item.date).toLocaleDateString());
            
            window.weeklyChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '播放量',
                        data: data.map(item => parseInt(item.totalPlays || 0)),
                        borderColor: '#ff6b6b',
                        backgroundColor: 'rgba(255, 107, 107, 0.1)',
                        tension: 0.4
                    }, {
                        label: '点赞数',
                        data: data.map(item => parseInt(item.totalLikes || 0)),
                        borderColor: '#4ecdc4',
                        backgroundColor: 'rgba(78, 205, 196, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top',
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 绘制月度图表
        function drawMonthlyChart(data) {
            const ctx = document.getElementById('monthlyChart').getContext('2d');
            
            if (window.monthlyChart) {
                window.monthlyChart.destroy();
            }
            
            window.monthlyChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['播放量', '点赞数', '评论数', '分享数', '新增粉丝'],
                    datasets: [{
                        label: '月度数据',
                        data: [
                            data.reduce((sum, item) => sum + parseInt(item.totalPlays || 0), 0),
                            data.reduce((sum, item) => sum + parseInt(item.totalLikes || 0), 0),
                            data.reduce((sum, item) => sum + parseInt(item.totalComments || 0), 0),
                            data.reduce((sum, item) => sum + parseInt(item.totalShares || 0), 0),
                            data.reduce((sum, item) => sum + parseInt(item.netFollowers || 0), 0)
                        ],
                        backgroundColor: [
                            '#ff6b6b',
                            '#4ecdc4',
                            '#45b7d1',
                            '#96ceb4',
                            '#ffeaa7'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 绘制转化漏斗图
        function drawFunnelChart(stats) {
            const ctx = document.getElementById('funnelChart').getContext('2d');
            
            if (window.funnelChart) {
                window.funnelChart.destroy();
            }
            
            window.funnelChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['播放量', '点赞数', '转化数'],
                    datasets: [{
                        data: [stats.totalPlays, stats.totalLikes, stats.totalConversions * 100], // 放大转化数以便显示
                        backgroundColor: ['#ff6b6b', '#4ecdc4', '#dda0dd']
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
        
        // 更新仪表板
        function updateDashboard() {
            if (dailyData.length === 0) return;
            
            // 计算总体数据
            const totalPlays = dailyData.reduce((sum, item) => sum + parseInt(item.totalPlays || 0), 0);
            const totalFollowers = Math.max(...dailyData.map(item => parseInt(item.totalFollowers || 0)));
            const totalConversions = dailyData.reduce((sum, item) => sum + parseInt(item.conversions || 0), 0);
            
            document.getElementById('dashboardTotalPlays').textContent = formatNumber(totalPlays);
            document.getElementById('dashboardTotalFollowers').textContent = formatNumber(totalFollowers);
            document.getElementById('dashboardTotalConversions').textContent = formatNumber(totalConversions);
            
            // 更新最近数据表格
            updateRecentDataTable();
            
            // 绘制趋势图
            drawDashboardTrendChart();
        }
        
        // 更新最近数据表格
        function updateRecentDataTable() {
            const tbody = document.getElementById('recentDataTable');
            tbody.innerHTML = '';
            
            // 获取最近7天数据
            const recentData = [...dailyData]
                .sort((a, b) => new Date(b.date) - new Date(a.date))
                .slice(0, 7);
            
            recentData.forEach(data => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${new Date(data.date).toLocaleDateString()}</td>
                    <td>${data.videoCount || 0}</td>
                    <td>${formatNumber(data.totalPlays || 0)}</td>
                    <td>${formatNumber(data.totalLikes || 0)}</td>
                    <td>${data.netFollowers || 0}</td>
                    <td>${data.conversions || 0}</td>
                    <td>${data.engagementRate || 0}%</td>
                `;
            });
        }
        
        // 绘制仪表板趋势图
        function drawDashboardTrendChart() {
            const ctx = document.getElementById('dashboardTrendChart').getContext('2d');
            
            if (window.dashboardChart) {
                window.dashboardChart.destroy();
            }
            
            // 获取最近30天数据
            const recentData = [...dailyData]
                .sort((a, b) => new Date(a.date) - new Date(b.date))
                .slice(-30);
            
            window.dashboardChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: recentData.map(item => new Date(item.date).toLocaleDateString()),
                    datasets: [{
                        label: '播放量',
                        data: recentData.map(item => parseInt(item.totalPlays || 0)),
                        borderColor: '#ff6b6b',
                        backgroundColor: 'rgba(255, 107, 107, 0.1)',
                        tension: 0.4
                    }, {
                        label: '新增粉丝',
                        data: recentData.map(item => parseInt(item.netFollowers || 0)),
                        borderColor: '#45b7d1',
                        backgroundColor: 'rgba(69, 183, 209, 0.1)',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            position: 'left'
                        },
                        y1: {
                            beginAtZero: true,
                            position: 'right',
                            grid: {
                                drawOnChartArea: false,
                            },
                        }
                    }
                }
            });
        }
        
        // 导出数据
        function exportData() {
            if (dailyData.length === 0) {
                alert('❌ 暂无数据可导出');
                return;
            }
            
            // 生成CSV内容
            const headers = ['日期', '记录人', '视频数', '播放量', '点赞数', '评论数', '分享数', '收藏数', '新增粉丝', '取关数', '净增粉丝', '私信数', '微信添加', '体验预约', '成交数', '内容成本', '广告成本', '人力成本', '总成本', '点赞率', '评论率', '分享率', '互动率', '获客成本', '备注'];
            
            const rows = dailyData.map(data => [
                data.date,
                data.recorder,
                data.videoCount,
                data.totalPlays,
                data.totalLikes,
                data.totalComments,
                data.totalShares,
                data.totalCollects,
                data.newFollowers,
                data.unfollowers,
                data.netFollowers,
                data.privateMessages,
                data.wechatAdds,
                data.trialBookings,
                data.conversions,
                data.contentCost,
                data.adCost,
                data.laborCost,
                data.totalCost,
                data.likeRate,
                data.commentRate,
                data.shareRate,
                data.engagementRate,
                data.acquisitionCost,
                data.notes
            ]);
            
            const csvContent = [headers, ...rows]
                .map(row => row.map(cell => `"${cell || ''}"`).join(','))
                .join('\n');
            
            // 下载文件
            const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `抖音数据统计_${new Date().toISOString().split('T')[0]}.csv`;
            link.click();
            
            alert('✅ 数据导出成功！');
        }
        
        // 生成周报
        function generateWeeklyReport() {
            const selectedWeek = document.getElementById('weekSelect').value;
            if (!selectedWeek) {
                alert('请先选择要分析的周次');
                return;
            }
            
            alert('📊 周报生成功能开发中，敬请期待！');
        }
        
        // 生成月报
        function generateMonthlyReport() {
            const selectedMonth = document.getElementById('monthSelect').value;
            if (!selectedMonth) {
                alert('请先选择要分析的月份');
                return;
            }
            
            alert('📈 月报生成功能开发中，敬请期待！');
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 如果有数据，更新仪表板
            if (dailyData.length > 0) {
                updateDashboard();
            }
        });
    </script>
</body>
</html>